/*
 * @Description: 聊天室 - 首页相关即时通讯
 * @Author: Yong
 * @Date: 2021-10-08 20:39:26
 * @LastEditTime: 2021-10-10 21:18:36
 */

import { Context, Application } from '@midwayjs/socketio'
import { App, Provide, Inject, OnWSConnection, WSController, WSEmit, OnWSDisConnection } from '@midwayjs/decorator'
import { FriendsService } from '../service/Friends'

const user: { [k: string]: any } = {}
@Provide()
@WSController('/home')
export class HomeSocketController {
    @Inject()
    ctx: Context

    @App()
    app: Application

    @Inject()
    friendsService: FriendsService

    // 注册用户ID
    userID:string = null

    @OnWSConnection()
    async onConnection () {
        console.log('home客户端连接成功, socketId ==> ', this.ctx.id)
        // 获取当前登录用户的userID
        const userID = this.ctx.handshake.query.userID
        console.log('userID==>', userID)        
        this.userID = userID.toString()
        user[userID.toString()] = this.ctx.id

        // 获取好友申请列表个数
        const applyFriendTotal = (await this.friendsService.getFriends(userID.toString(), 2)).total
        // 获取好友消息列表
        const friendMsgList = (await this.friendsService.getFriends(userID.toString(), 0))

        this.ctx.emit('initHomeData', { applyFriendTotal, friendMsgList })
    }


    // 更新申请好友个数
    @WSEmit('updateApplyFriendTotal')
    async updateApplyFriendTotal () {
        const applyFriendTotal = (await this.friendsService.getFriends(this.userID.toString(), 2)).total
        return { applyFriendTotal }
    }

    // 更新好友消息
    @WSEmit('updateFriendMsgList')
    async updateFriendMsgList () {
        const friendMsgList  = (await this.friendsService.getFriends(this.userID.toString(), 0)).total
        return { friendMsgList }
    }

    // 监听用户离开
    @OnWSDisConnection()
    async disConnection () {
        if (user.hasOwnProperty(this.userID)) {
            delete user[this.userID]
            this.userID = null
            console.log(`${this.ctx.id}离开`)
        }
    }
}